package eerbaar.v2.app.view;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;

import eerbaar.elements.IElement;
import eerbaar.game.IGame;
import eerbaar.persona.IPersona;
import eerbaar.v2.app.GameHelper;
import eerbaar.v2.app.core.Entity;
import eerbaar.v2.app.core.ISprite;
import eerbaar.v2.app.tasks.IGameTask.Priority;
import eerbaar.v2.app.view2.ImageId;
import eerbaar.v2.app.view2.ImageStore;
import eerbaar.v2.graphics.rect.RectCenter;

public class View implements IView {

    private static final View instance = new View();

    public static View getInstance() {
        return instance;
    }

    private final List<Entity> entities = new ArrayList<Entity>();
    private final Squares squares = new Squares();

    private final ImageStore store = new ImageStore();

    private View() {
        //
    }

    @Override
    public void draw(Graphics2D g) {

        this.squares.draw(g);

        IGame game = GameHelper.getGame();
        if (game == null) {
            return;
        }

        IElement[] elements = game.getArea().getElements();
        for (IElement e : elements) {

            if (e instanceof IPersona) {
                continue;
            }

            ImageId id = new ImageId(e.getName(), null, null);
            ISprite sprite = this.store.getImage(id);

            int x = e.getPosition().getX() * 50;
            int y = e.getPosition().getY() * 50;
            Rectangle r = new Rectangle(x, y, 50, 50);
            Image image = sprite.getImage();
            Point p = RectCenter.calcTopLeft(r, image.getWidth(null),
                    image.getHeight(null));

            sprite.draw(g, p.x, p.y);
        }

        for (int i = 0; i < this.entities.size(); i++) {
            Entity entity = this.entities.get(i);
            entity.draw(g);
        }
    }

    @Override
    public int getHeight() {
        return 500;
    }

    @Override
    public Priority getPriority() {
        return Priority.LAST;
    }

    @Override
    public int getSquareHeight() {
        return 50;
    }

    @Override
    public Squares getSquares() {
        return this.squares;
    }

    @Override
    public int getSquareWidth() {
        return 50;
    }

    @Override
    public int getWidth() {
        return 500;
    }

}
